<script setup lang="ts">
import { ref, onMounted } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormItemConfig,PurchasePlanModel,PurchasePlan } from "@/pages/purchase/components/PurchasePlan"


import { getPlanTypeLabel,getStatusLabel,planApi } from '@/pages/purchase/components/PurchasePlan'
import { defineEmits } from 'vue';

import {planPassApi} from '@/pages/purchase/components/PurchasePass'
import { monitorApi } from '../components/PurchaseMonitor'

const emit = defineEmits(['go-to-purchase-detail', 'go-to-purchase-monitor','go-to-purchase-detail-onlyRead']);
const createFormConfig = <T extends FormItemConfig[]>(config: [...T]) => config;
const ListFields = [
    {
      label: 'Id',
      prop: 'planId',
      type: 'input',
      disabled: false,
      width: "50px",
    },
    {
      label: '名称',
      prop: 'name',
      type: 'input',
      width: "200px",
      slot: true,
    },
    {
      label: '查看',
      prop: 'check',
      slot: true,
      width: "135px"
    },
    {
      label: '状态',
      prop: 'status',
      type: 'input',
      slot: true,
      width:"120px"      
    },
    {
      label: '类型',
      prop: 'type',
      type: 'input',
      slot: true,
      width: "80px",
    },
    {
      label: '描述',
      prop: 'description',
      type: 'textarea',
    
    },
    {
      label: '部门',
      prop: 'department',
      type: 'input',
      width: "120px",
    },
    {
      label: '计划人',
      prop: 'plannerName',
      type: 'input',
      width: "100px",
      
    },
    {
      label: '预算金额￥',
      prop: 'budget',
      type: 'input',
      slot: true,
      width:"150px"
    },

    {
      label: '开始时间',
      prop: 'startTime',
      type: 'datetime',
      width: "166px",
    },
    {
      label: '结束时间',
      prop: 'endTime',
      type: 'datetime',
      width: "166px",
    },
    {
      label: '操作',
      prop: 'action',
      slot: true,
      width: "220px"
    },
  ];
const formConfig = createFormConfig([
  { 
    type: 'input', 
    label: '计划名称', 
    prop: 'name', 
    placeholder: '请输入计划名称' 
  },
  { 
    type: 'select', 
    label: '计划类型', 
    prop: 'type', 
    placeholder: '请选择计划类型', 
    options: [
      { label: '年度计划', value: 1 },
      { label: '季度计划', value: 2 },
      { label: '临时计划', value: 3 },
    ] 
  },
  { 
    type: 'input', 
    label: '描述', 
    prop: 'description', 
    placeholder: '请输入描述' 
  },
  {
    type: 'select',
    label: '部门',
    prop: 'department',
    placeholder: '请选择部门',
    options: [
      { label: '财务部', value: '财务部' },
      { label: '技术研发部', value: '技术研发部' },
      { label: '市场营销部', value: '市场营销部' },
      { label: '人力资源部', value: '人力资源部' },
      { label: '生产制造部', value: '生产制造部' },
      { label: '客户服务部', value: '客户服务部' },
      { label: '行政管理部', value: '行政管理部' },
      { label: '品质管理部', value: '品质管理部' }
    ]
  },
  { 
    type: 'input', 
    label: '负责人', 
    prop: 'plannerName', 
    placeholder: '请输入负责人姓名' 
  },
  { 
    type: 'input', 
    label: '预算金额￥', 
    prop: 'budget', 
    placeholder: '请输入金额', 
    inputType: 'number' 
  },
  { 
    type: 'datetime', 
    label: '开始时间', 
    prop: 'startTime', 
    placeholder: '选择开始时间' 
  },
  { 
    type: 'datetime', 
    label: '结束时间', 
    prop: 'endTime', 
    placeholder: '选择结束时间' 
  }
])

let purchasePlanList = ref<PurchasePlan[]>();
const formModel = ref<PurchasePlanModel>({
  IsUpdate:null,
  planId:null,
  name: '',
  type: null,

  description: '',
  department: '',
  plannerName: '',

  budget: null,// decimal(10,2)
  status: 1,

  startTime: '',
  endTime: '',
})
const titleName = "审批申请";
const searchMessage = ref({
  name:'',
  department:'',
})

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(100)

const title = ref('')
const visibleDrawer = ref(false)

onMounted(async () => {
  init();
})
const init = async () => {
  getDataListWithCondition();
}
const getDataListWithCondition = async () => {
  const num = ref(1 )
    let params = {
        page: pageNum.value,
        size: pageSize.value,
        status:num.value,
        name: searchMessage.value.name ? searchMessage.value.name : null,
        department: searchMessage.value.department ? searchMessage.value.department : null,
    }
    console.log(params);
    const purchasePlanListResponse = await planPassApi.getPurchasePlansForCheck(params);
    purchasePlanList.value = purchasePlanListResponse.data.records;
    console.log(purchasePlanListResponse)    
    console.log(purchasePlanList)
    total.value = purchasePlanListResponse.data.total;
}
getDataListWithCondition();

const handleSubmit = async () => {
  if (formModel.value.IsUpdate) {
      await planApi.updatePlan(formModel.value.planId!, formModel.value)
      ElMessage.success('更新成功')
    } else {
      await planApi.addPlan(formModel.value)
      ElMessage.success('添加成功')
    }
    visibleDrawer.value = false
    getDataListWithCondition()
}


const decision = ref("")
const changeState =  async(planId:number,status:number) => {
  await monitorApi.updatePurchasePlanStatus(planId, status)
  getDataListWithCondition()
}

const changeStateBox = (planId:number,status:number) => {
  if(status==3){
    decision.value= "你确定要通过这个采购计划吗"
  }else if(status==0){
    decision.value= "你确定要驳回申请吗"
  }
    ElMessageBox.confirm(
        `${decision.value}`,
        '注意：请在决定之前认真查看采购设备列表',
        {
            confirmButtonText: '操作',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        changeState(planId,status)
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '操作取消',
        })
    })
}

const search = () => {
    getDataListWithCondition()
    ElMessage('获取成功')
}
const searchWithNoCondition = () => {
    searchMessage.value = { name: '', department: '' };
    getDataListWithCondition()
    ElMessage('获取成功')
}

const onSizeChange = (size: number) => {
    pageSize.value = size
    getDataListWithCondition()
    ElMessage('获取成功')

}
const onCurrentChange = (num: number) => {
    pageNum.value = num
    getDataListWithCondition()
    ElMessage('获取成功')
}

const goToPurchaseDetail = (row:PurchasePlan) => {
  emit('go-to-purchase-detail-onlyRead',row.planId,row.name,row.status);
  console.log('向父组件触发了 "go-to-purchase-detail-onlyRead" 事件。'+ row.planId);
}


</script>

<template>
  <el-card class="page-container">
    <template #header>
        <div class="header">
            <span>{{ titleName }}</span>
        </div>
    </template>
    <el-form inline>
      <el-form-item label="名称:">
          <el-input v-model="searchMessage.name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="部门:">
          <el-input v-model="searchMessage.department" placeholder="请输入"></el-input>
      </el-form-item>       
      <el-form-item>
      <el-button type="primary" @click="search()">搜索</el-button>
         <el-button @click="searchWithNoCondition()">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="purchasePlanList" style="width: 100%">
      <el-table-column
        v-for="col in ListFields"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
      >
        <template v-if="col.slot" #default="scope">
          <template v-if="col.prop === 'check'" >
            <el-button
              plain
              type="primary"              
              @click="goToPurchaseDetail(scope.row)"
            >计划设备列表</el-button>
          </template>
          <template v-else-if="col.prop === 'type'">
            {{ getPlanTypeLabel(scope.row.type) }}
          </template>
          <template v-else-if="col.prop === 'budget'">
            {{ scope.row.budget?.toLocaleString() ?? 'N/A' }}
          </template>
          <template v-else-if="col.prop === 'status'">
            {{ getStatusLabel(scope.row.status) }}
          </template>
          <template v-else-if="col.prop === 'action'">
            <el-button
              plain
              type="primary"
              @click="changeStateBox(scope.row.planId,3)"
            >通过审批</el-button> 
            <el-button
              plain
              type="danger"
              @click="changeStateBox(scope.row.planId,0)"
            >驳回申请</el-button>
          </template>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
        layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
        @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

        
  <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
    <el-form :model="formModel" label-width="120px">
      <template v-for="(item, index) in formConfig" :key="index">
        <el-form-item v-if="item.type === 'input'" :label="item.label">
          <el-input 
            v-model="formModel[item.prop]"
            :placeholder="item.placeholder"
          ></el-input>
        </el-form-item>
        
        <el-form-item v-else-if="item.type === 'datetime'" :label="item.label">
          <el-date-picker
            v-model="formModel[item.prop]"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="item.placeholder"
          />
        </el-form-item>

        <el-form-item v-else-if="item.type === 'select'" :label="item.label">
          <el-select
            v-model="formModel[item.prop]"
            :placeholder="item.placeholder"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="option in item.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </template>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交计划</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>

    
  </el-card>
</template>



<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    max-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}

.name-cell-wrapper {
  position: relative;
  display: inline-block;
}

.name-link {
  text-decoration: none;
  color: #67C23A;
  cursor: pointer;
  outline: none;
}

.focus-tooltip {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 10;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out;
  top: 100%; 
  left: 50%;
  transform: translateX(-50%) translateY(5px);
}

.name-link:focus + .focus-tooltip {
  opacity: 1;
  visibility: visible;
}
</style>